<template>
  <router-view #default="{ Component }" :include="getCache" :max="8">
    <keep-alive>
      <component :is="Component" />
    </keep-alive>
  </router-view>
</template>

<script>
import { mapGetters, mapState } from 'vuex';
import { common } from '@/utils';

export default {
  name: 'app',

  data() {
    return {
      exitCount: 0,
    };
  },

  computed: {
    ...mapState('common', ['ttid', 'mode', 'hotUpdateUrl', 'token', 'isHotUpdate']),
    ...mapGetters('common', ['getCache']),
  },

  mounted() {
    this.init();
  },

  unmounted() {
    if (window.plus) {
      window.plus.key.removeEventListener('backbutton', this.onHandleBack);
    }
  },

  methods: {
    init() {
      common.plusReady(() => {
        this.$hotUpdate.init({
          url: this.hotUpdateUrl,
          ttid: this.ttid,
          mode: this.mode,
        });

        if (this.token && this.isHotUpdate) {
          this.$hotUpdate.checkUpdate();
        }

        window.plus.screen.lockOrientation('portrait-primary');
        window.plus.navigator.setStatusBarStyle('light');
        window.plus.navigator.setStatusBarBackground('#1e5bc6');
        window.plus.key.addEventListener('backbutton', this.onHandleBack, false);
      });
    },

    onHandleBack() {
      const whiteList = ['/login', '/home/homePage', '/404'];

      if (whiteList.includes(this.$route.path)) {
        if (this.exitCount < 1) {
          this.exitCount++;
          this.$toast({
            message: this.$t('clickExitAgain'),
            position: 'bottom',
          });

          setTimeout(() => {
            this.exitCount = 0;
          }, 3000);
        } else {
          window.plus.runtime.quit();
        }
      } else {
        this.$router.back();
      }
    },
  },
};
</script>
